package com.fxhy.controller;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baby.bean.UserInfo;
import com.baby.constants.Constants;
import com.baby.myutils.DateUtils;
import com.baby.myutils.JWTUtil;
import com.baby.po.ResponseBodyEntity;
import com.fxhy.bean.AgentUser;
import com.fxhy.bean.IdentifiInfo;
import com.fxhy.bean.custom.AgentUserCustom;
import com.fxhy.service.IdentifiInfoService;
import com.fxhy.service.SmsService;
import com.fxhy.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 手机短讯
 * @author lifengyao
 *
 */
@Slf4j
@RestController
@RequestMapping("sms")
@Api(value="短信接口")
public class SmsApi {

	@Autowired
	private SmsService smsService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private IdentifiInfoService identifiInfoService;
	
	/**
	 * 发送验证码
	 * @return
	 */
	@ApiOperation("发送验证码")
	@RequestMapping(value = "sendMsgToPhone",method = RequestMethod.POST)
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="phoneNum",dataType="String",required=true,value="手机号",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="virifyCode",dataType="String",required=true,value="图形验证码",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="token",dataType="String",required=true,value="token",defaultValue="")
		        })
	public ResponseBodyEntity sendMsgToPhone(String phoneNum,String virifyCode,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		log.info("输入的图形验证码:{},token:{}",virifyCode,token);
		if(!JWTUtil.verify(token, virifyCode, Constants.KAPTCHA_KEY)) {
			log.error("图形验证码错误");
			responseBodyEntity.setMsg("图形验证码错误!");
			responseBodyEntity.setState(Constants.FAILURE);
			return responseBodyEntity;
		}
		
		if(phoneNum != null && !phoneNum.equals("")){
			//校验手机号码
			String REG_PHONE = "^((19[8,9])|(166)|(14[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))[0-9]{8}$";
	        Pattern p = Pattern.compile(REG_PHONE);
			Matcher m = p.matcher(phoneNum);
			if(!m.matches()){
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("手机号码格式错误!");
				return responseBodyEntity;
			}
	        
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo == null || userInfo.getUserId() == null) {//不存在用户
				userInfo = userService.registerUserByPhone(phoneNum);
				if(userInfo != null && userInfo.getUserId() != null){
					if(smsService.sendMsg(phoneNum,userInfo)){
						responseBodyEntity.setData("");
						responseBodyEntity.setState(Constants.SUCCEED);
						responseBodyEntity.setMsg("发送登录验证码成功!");
					}else{
						responseBodyEntity.setData(userInfo);
						responseBodyEntity.setMsg("登录短信发送失败!请稍后再试!");
						responseBodyEntity.setState(Constants.FAILURE);
						return responseBodyEntity;
					}
				}else{
					responseBodyEntity.setState(Constants.FAILURE);
					responseBodyEntity.setMsg("手机号码注册失败!请稍后再试!");
				}
			}else{
				if(smsService.sendMsg(phoneNum,userInfo)){
					responseBodyEntity.setData("");
					responseBodyEntity.setState(Constants.SUCCEED);
					responseBodyEntity.setMsg("发送登录验证码成功!");
				}else{
					responseBodyEntity.setData(userInfo);
					responseBodyEntity.setMsg("登录短信发送失败!请稍后再试!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}
		}else{
			responseBodyEntity.setState(Constants.FAILURE);
			responseBodyEntity.setMsg("手机号码不能为空!");
		}
		return responseBodyEntity;
	}
	
	
	@ApiOperation("选择认证类型   发送验证码")
	@RequestMapping(value = "sendMsgToPhoneByIdentify",method = RequestMethod.POST)
	public ResponseBodyEntity sendMsgToPhoneByIdentify(String phoneNum,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		if(phoneNum != null && !phoneNum.equals("")){
			//校验手机号码
			String REG_PHONE = "^((19[8,9])|(166)|(14[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))[0-9]{8}$";
	        Pattern p = Pattern.compile(REG_PHONE);
			Matcher m = p.matcher(phoneNum);
			if(!m.matches()){
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("号码格式错误!");
				return responseBodyEntity;
			}
			
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo == null) {//存在用户
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("手机号码不存在!");
				return responseBodyEntity;
			}else{
				if(userInfo.getIsIdentifi() == -1){
					if(userInfo.getRoleId() != -1){
						responseBodyEntity.setData(userInfo);
						responseBodyEntity.setMsg("你已选择过认证类型!自动刷新数据!若无效,请重新登录!");
						responseBodyEntity.setState(Constants.FAILURE);
					}else{
						//查找是否存在
						IdentifiInfo id = identifiInfoService.findIdentifiInfoByUserId(userInfo.getUserId());
						if(id != null && id.getIdentifiId() != null){
							id.setUserId(userInfo.getUserId());
							if(smsService.sendMsg(phoneNum,id)){
								responseBodyEntity.setData("");
								responseBodyEntity.setState(Constants.SUCCEED);
								responseBodyEntity.setMsg("身份验证码发送成功!请注意查收!");
							}else{
								responseBodyEntity.setData(userInfo);
								responseBodyEntity.setMsg("身份短信发送失败!请稍后再试!");
								responseBodyEntity.setState(Constants.FAILURE);
								return responseBodyEntity;
							}
						}else{
							IdentifiInfo identify = new IdentifiInfo();
							identify.setUserId(userInfo.getUserId());
							identify.setRoleId(-1);
							identify.setStatus(1);
							identify.setCreateTime(DateUtils.getNowDate());
							identify.setCreateUser(userInfo.getNickName());
							identify.setUpdateTime(DateUtils.getNowDate());
							identify.setUpdateUser(userInfo.getNickName());
							if(smsService.sendMsg(phoneNum,identify)){
								responseBodyEntity.setData("");
								responseBodyEntity.setState(Constants.SUCCEED);
								responseBodyEntity.setMsg("身份验证码发送成功!请注意查收!");
							}else{
								responseBodyEntity.setData(userInfo);
								responseBodyEntity.setMsg("短信发送失败!请稍后再试!");
								responseBodyEntity.setState(Constants.FAILURE);
								return responseBodyEntity;
							}
						}
					}
				}else{		
					responseBodyEntity.setData(userInfo);
					responseBodyEntity.setMsg("你已完成了认证!请刷新界面!\n若刷新无效!请重新登录!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}
		}
		return responseBodyEntity;
	}
	
	@ApiOperation("上传身份证   发送验证码")
	@RequestMapping(value = "sendMsgToPhoneByIDcard",method = RequestMethod.POST)
	public ResponseBodyEntity sendMsgToPhoneByIDcard(String phoneNum,String token){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		if(phoneNum != null && !phoneNum.equals("")){
			//校验手机号码
			String REG_PHONE = "^((19[8,9])|(166)|(14[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))[0-9]{8}$";
	        Pattern p = Pattern.compile(REG_PHONE);
			Matcher m = p.matcher(phoneNum);
			if(!m.matches()){
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("号码格式错误!");
				return responseBodyEntity;
			}
			
			AgentUser userInfo = userService.findUserByPhone(phoneNum);
			if(userInfo == null) {//存在用户
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("手机号码不存在!");
				return responseBodyEntity;
			}else{
				if(userInfo.getIsIdentifi() == -1){
					//查找是否存在
					IdentifiInfo id = identifiInfoService.findIdentifiInfoByUserId(userInfo.getUserId());
					if(id != null && id.getIdentifiId() != null){
						id.setUserId(userInfo.getUserId());
						if(smsService.sendMsg(phoneNum,id)){
							responseBodyEntity.setData("");
							responseBodyEntity.setState(Constants.SUCCEED);
							responseBodyEntity.setMsg("身份验证码发送成功!请注意查收!");
						}else{
							responseBodyEntity.setData(userInfo);
							responseBodyEntity.setMsg("短信发送失败!请稍后再试!");
							responseBodyEntity.setState(Constants.FAILURE);
							return responseBodyEntity;
						}
					}else{
						IdentifiInfo identify = new IdentifiInfo();
						identify.setUserId(userInfo.getUserId());
						if(smsService.sendMsg(phoneNum,identify)){
							responseBodyEntity.setData("");
							responseBodyEntity.setState(Constants.SUCCEED);
							responseBodyEntity.setMsg("身份验证码发送成功!请注意查收!");
						}else{
							responseBodyEntity.setData(userInfo);
							responseBodyEntity.setMsg("短信发送失败!请稍后再试!");
							responseBodyEntity.setState(Constants.FAILURE);
							return responseBodyEntity;
						}
					}
				}else{		
					responseBodyEntity.setData(userInfo);
					responseBodyEntity.setMsg("你已完成了认证!请刷新界面!\n若刷新无效!请重新登录!");
					responseBodyEntity.setState(Constants.FAILURE);
					return responseBodyEntity;
				}
			}
		}
		
		return responseBodyEntity;
	}
	
	
	/**
	 * 分享注册    -- 发送验证码   -- 注册    -- 绑定代理关系
	 * @return
	 */
	@ApiOperation("分享注册    -- 发送验证码   -- 注册   -- 绑定代理关系")
	@RequestMapping(value = "sendMsgByRegist",method = RequestMethod.POST)
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="phoneNum",dataType="String",required=true,value="手机号",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="inviteCode",dataType="String",required=true,value="上代理邀请码",defaultValue=""),
		        })
	public ResponseBodyEntity sendMsgByRegist(String phoneNum,String inviteCode){
		log.info("发送验证码,手机号为:{}",phoneNum);
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		if(phoneNum != null && !phoneNum.equals("")){
			if(inviteCode != null && !inviteCode.equals("")){
				if(userService.findUserCountFromInviteUser(phoneNum) > 0){
					////已绑定用户直接跳转
					responseBodyEntity.setState("3");
					responseBodyEntity.setMsg("该用户已被绑定!直接跳转到下载界面？");
				}else{
					AgentUserCustom  agent = userService.findByInviteCode(inviteCode);
					//没绑定过得
					if(userService.findUserCountByPhone(phoneNum) > 0){
						//注册过的
						responseBodyEntity.setState("3");
						responseBodyEntity.setMsg("该用户已经注册过啦!已无法绑定！直接跳转到下载界面？");
					}else{
						//没有注册过的
						if(agent != null && agent.getUserId() != null){
							UserInfo user = userService.registerUserByPhone(phoneNum,-1);
							if(user != null && user.getUserId() != null){
								//绑定关系
								if(smsService.sendMsg(phoneNum,user)){
									responseBodyEntity.setState(Constants.SUCCEED);
									responseBodyEntity.setMsg("发送短信成功!");
								}else{
									responseBodyEntity.setState(Constants.FAILURE);
									responseBodyEntity.setMsg("发送短信失败!");
								}
							}else{
								responseBodyEntity.setState(Constants.FAILURE);
								responseBodyEntity.setMsg("服务器内部错误!绑定失败!");
							}
						}else{
							responseBodyEntity.setState(Constants.FAILURE);
							responseBodyEntity.setMsg("信息不实!绑定失败!");
						}
					}
				}
			}else{
				responseBodyEntity.setState(Constants.FAILURE);
				responseBodyEntity.setMsg("信息不实!绑定失败!");
			}
		}else{
			responseBodyEntity.setState(Constants.FAILURE);
			responseBodyEntity.setMsg("手机号码不能为空!");
		}
		return responseBodyEntity;
	}
}
